<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\JsonResponse;
use App\Http\Requests\Admin\LoginRequest;
use App\Transformers\Admin\AdminUserTransformer;
use Illuminate\Support\Facades\Auth;
use App\Models\AdminUser;
use App\Models\User;
use App\Models\AdminRole;
use App\Events\WeChatNoticeEvent;

class LoginController extends Controller
{


    public function login()
    {
        return view('admins.login');
    }

    /**
     * @return JsonResponse
     */
    public function doLogin(LoginRequest $request)
    {
        $credentials = $request->only(['phone', 'password']);
        if (!Auth::guard('admin')->attempt($credentials)) {
            return redirect()->route('admin.login')->with('warning', '登录失败!');
        }
        $admin_user = Auth::guard('admin')->user();
        //验证是否被冻结
        if($admin_user->state == 2){
            Auth::guard('admin')->logout();
            return redirect()->route('admin.login')->with('warning', '帐号已被冻结');
        }
        //验证审核状态
        if($admin_user->available != 1){
            Auth::guard('admin')->logout();
            return redirect()->route('admin.login')->with('warning', get_user_available($admin_user->available));
        }
        //更新最后一次登录IP
        $admin_user->last_ip = $request->getClientIp();
        $admin_user->save();
        $admin_user->load('third');
        if(!empty(optional($admin_user->third)->push_type) && !empty(optional($admin_user->third)->wx_open_id)){
            $type = json_decode($admin_user->third->push_type,true);
            if($type['log']['val'] == 'true'){
                event(new WeChatNoticeEvent($admin_user->third->wx_open_id,"用户账号在电脑端登录成功"));
            }
        }
        return redirect('admin/')->with('success', '登录成功');
    }

    public function logout()
    {
        Auth::guard('admin')->logout();

        return redirect()->route('admin.login')->with('success', '退出成功');
    }

}